# Create your views here.
from django.http import HttpResponse, Http404, HttpResponseRedirect, \
    HttpResponseServerError
from django.shortcuts import render_to_response

from models import ClusterDetection, ClusterFinder, CompositeExperiment, \
    CompositeProtocol, Project, Simulation, Simulator, WebService

urlmap = {'clusterdetection':ClusterDetection, 
          'clusterfinder':ClusterFinder, 
          'compositeexperiment':CompositeExperiment,
          'compositeprotocol':CompositeProtocol,
          'project':{'model':Project,
                     'template':'simdb/browser/project.xml'},
          'simulation':Simulation, 
          'simulator':Simulator,
          'webservice':{'model':WebService,
                        'template':'simdb/browser/webservice.xml'}
          }

def object_request(request, element, id):
    try:
        obj = urlmap[element]['model'].objects.get(id=int(id))
    except:
        raise Http404

    if request.method == 'GET':
        return render_to_response(urlmap[element]['template'],
                                  {'element':obj}, mimetype='text/xml')
    elif request.method == 'PUT':
        put_object(request, element, id)
    elif request.method == 'DELETE':
        try:
            obj.delete()
            return HttpResponse('OK')
        except:
            return HttpResponseServerError('Failed to delete',status)

def collection_request(request, element):
    if not element in urlmap:
        raise Http404
    if request.method == 'GET':
        listing = {}
        listing['element'] = element
        listing['items'] = urlmap[element]['model'].objects.all()
        return render_to_response('browser/element_index.html', 
                                  {'listing': listing})
    elif request.method == 'POST':
        return HttpResponse('Created',status=201)

def elements_index(request):
    return render_to_response('browser/elements_index.html', 
                              {'listing': urlmap})
